/**
 * 使用 wait 回收子进程，并输出子进程退出状态
*/

#include <stdio.h>
#include <stdlib.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void out_progress_exit_status(int pid, int status)
{

    if (WIFEXITED(status))
    {
        printf("%d normal exit, code is %d\n", pid, WEXITSTATUS(status));
    }
    else if (WIFSIGNALED(status))
    {
        printf("%d abnormal exit, code is %d\n", pid, WTERMSIG(status));
    }
    else if (WIFSTOPPED(status))
    {
        printf("%d stoped exit, code is %d\n", WSTOPSIG(status));
    }
}

int main()
{

    pid_t pid = fork();

    if (0 > pid)
    {
        perror("fork error: ");
        exit(EXIT_FAILURE);
    }
    else if (0 == pid)
    {
        printf("I am child progress is id %d\n", getpid());
        exit(3);
    }

    int status;
    pid = waitpid(0, &status, WUNTRACED);
    out_progress_exit_status(pid, status);

    pid = fork();
    if (0 > pid)
    {
        perror("fork error: ");
        exit(EXIT_FAILURE);
    }
    else if (0 == pid)
    {
        printf("I am child progress is id %d\n", getpid());
        while (1)
        {
            sleep(1);
        }
    }

    do
    {
        pid = waitpid(pid, &status, WUNTRACED | WNOHANG);
        if (pid == 0)
        {
            sleep(1);
        }
    } while (pid == 0);
    out_progress_exit_status(pid, status);

    return 0;
}